<?php
/**
 * @package pmapi
 * @copyright Copyright (c)2014 Enrico Fagnoni
 * @license GNU General Public License version 3, or later
 *
 * @since 1.0.0
 */
 
defined('_JEXEC') or die;

if (!class_exists('LinkedDataView')) require(JPATH_COMPONENT.DS.'views'.DS.'linkeddata.php');

class PmapiViewUser extends LinkedDataView
{    
    protected 
        $users = null,
        $invoiceAddressType = 'pm:InvoicePoint',    // the ontology property to be uses for invoice address type
        $deliveryAddressType = 'pm:DeliveryPoint';  // the ontology property to be uses for delivery address type
 
     
    protected function _computeETag()
    {
        return md5(serialize($this->users));
    }
    
        
    public function GET_RequestProcessor($tpl = null) 
    {
        $params =JComponentHelper::getParams('com_pmapi');
        $vatidField = $params->get('vatid_field','taxid');
        $taxidField = $params->get('taxtid_field','vatid');
        // export view variables
        $this->invoiceAddressType  = $params->get('BT_type','pm:InvoicePoint');
        $this->deliveryAddressType = $params->get('ST_type','pm:DeliveryPoint');
        
        $userData = $this->get('Item');
        // set some default for userContact
        $userContact = new stdClass;
        $userContact->id = 'this';
        $userContact->deliveryContacts = array();
        $userContact->shopper_groups = isset($userData->shopper_groups)?$userData->shopper_groups:array();
        
        // populate some userContact field from userData scalar info
        foreach (array(
                    'user_is_vendor',
                    'virtuemart_vendor_id',
                    'customer_number') as $property){
            $userContact->$property = isset($userData->$property)?$userData->$property:'';
        }       
        // populate some userContact field from JUser table
        foreach (array(
                    'name',
                    'username',
                    'email') as $property){
            $userContact->$property = isset($userData->JUser->$property)?$userData->JUser->$property:'';
        }
                    
        // get other info about userContact and contacts addresses
        // PLEASE REMEMBER THAT OBJECT ARE ALWAYS PASSED AS REFERENCE.
        $this->users = array();   

        foreach ($userData->userInfo as $info ){
            if ($info->address_type=='BT'){
                $contact = $userContact;
            } else {
                $contact = new stdClass;
                $contact->id = $info->virtuemart_userinfo_id;
            }
            // attach data to contact
            foreach (get_object_vars($info) as $key => $value) {
                if ('_' != substr($key, 0, 1)) $contact->$key=$value;
            }
            
            // ensure that the minimum set of user fields has a default value
            $defaults = array (
                'id'                    => null,
                'user_is_vendor'        => null,
                'virtuemart_vendor_id'  => null,
                'customer_number'       => null,
                'username'              => null,
                // taxid and vatid are mandatory fields but non present as default in virtuemart:
                'taxid'                 => isset($contact->$taxidField)?$contact->$taxidField:null,
                'vatid'                 => isset($contact->$vatidField)?$contact->$vatidField:null,
                'company'               => '', 
                'name'                  => null,
                'username'              => null,
                'shopper_groups'        => array(),
                'address_type_name'     => null, 
                // for storical reasons an e-mail can be inserted in address_type_name field:
                'email'                 => (!empty($contact->address_type_name) 
                                               && $contact->address_type_name[0]=='@')?$contact->$taxidField:null,
                'title'                 => '',
                // ensure at least last_name is set if no company:
                'last_name'             => empty($contact->company)?'unknown':'',
                'first_name'            => '',
                'middle_name'           => '', 
                'phone_1'               => '',
                'phone_2'               => '',
                'fax'                   => '', 
                'address_1'             => '',
                'address_2'             => '', 
                'city'                  => '',
                'state'                 => '',
                'country'               => '',
                'zip'                   => '',
                'deliveryContacts'      => array(),
                'agentFor'              => array(),
                'vcardKind'             => empty($contact->company)?'Individual':'Organization',                           
            );
            foreach ( $defaults as $property=>$default) {
                if (!isset($contact->$property)) $contact->$property = $default;
            }
            
            // detect if contact is a delivery address for user or it is a related business entity
            // a delivery address contains a vatid or a tax id that is different from this
            // this user is acting as agent for the delivery address
            $isDeliveryContactPoint = ($contact != $userContact) &&(                      
                   (empty($info->$vatidField) && empty($info->$taxidField))
                || (isset($info->$vatidField) && $userContact->$vatidField && $info->$vatidField == $userContact->$vatidField )
                || (isset($info->$taxidField) && $userContact->$taxidField && $info->$taxidField == $userContact->$taxidField )
            );                 
            if ($isDeliveryContactPoint){
                // add delivery address to user contacts
                $userContact->deliveryContacts[] = $contact;
            } else {
                $this->users[]=$contact;
                if ($contact != $userContact) $userContact->agentFor[] = $contact->id;
            }                
        }

        return parent::GET_RequestProcessor($tpl);            
    } 
}

